
var builder = WebApplication.CreateBuilder(args);


// 读取允许的跨域域名列表
var allowedOrigins = builder.Configuration.GetSection("Cors:AllowedOrigins").Get<string[]>();

// 配置 CORS 策略
builder.Services.AddCors(options =>
{
    options.AddPolicy("DefaultCorsPolicy", policy =>
    {
        policy.WithOrigins(allowedOrigins ?? Array.Empty<string>())
              .AllowAnyHeader()
              .AllowAnyMethod()
              .AllowCredentials();
    });
});



builder.Services.AddReverseProxy()
    .LoadFromConfig(builder.Configuration.GetSection("ReverseProxy"));

//builder.services.AddReverseProxy().LoadFromConfig(new ConsulConfigProvider());//集成consul配置提供者


builder.Services.AddAuthentication("Bearer")
    .AddJwtBearer("Bearer", options =>
    {
        options.Authority = "https://localhost:7291/"; // 你的 IdentityService
        options.Audience = "api"; // token 里的 aud
        options.RequireHttpsMetadata = false;
        Console.WriteLine($"到了这里了");
        options.Events = new Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerEvents
        {
            
            OnAuthenticationFailed = context =>
            {
                Console.WriteLine($"JWT 验证失败: {context.Exception.Message}");
                return Task.CompletedTask;
            },
            OnTokenValidated = context =>
            {
                Console.WriteLine($"JWT 验证成功, subject: {context.Principal?.Identity?.Name}");
                return Task.CompletedTask;
            }
        };
    });

builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("IdentityPolicy", policy =>
    {
        policy.RequireAuthenticatedUser();
    });
});

var app = builder.Build();

app.UseRouting();



app.UseAuthentication(); // 可选
app.UseAuthorization();  // 可选


app.UseCors("DefaultCorsPolicy");
app.MapReverseProxy();   // 启用反向代理


app.Run();
